package com.mlm.mlmapp.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
@EActivity(R.layout.account_setting)
public class UserSettingActivity extends BaseActivity implements HTTPCons {
    AQuery aq;
    AjaxCallback<JSONObject> userSettingCB;
    AjaxCallback<JSONObject> uploadHeadimg;
    ActionSheetDialog dialog;
    @StringRes
    String msg_error;
    @StringRes
    String take_photo;
    @StringRes
    String from_photos;
    @Pref
    Prefs_ pref;
    @ViewById
    Button exit_login;
    @ViewById
    Button btn_mobile;
    @ViewById
    ImageView btn_headimg;
    @ViewById
    Button btn_name;
    @ColorRes
    int blacktext;
    @ColorRes
    int red;
    String oldmobile;
    private Bitmap photo;
    public static final String IMAGE_FILE_NAME = "avatar.jpg";

    @AfterViews
    void init() {
        String title = getTitle().toString();
        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }

        aq = new AQuery(this);
        oldmobile = pref.loginID().get();
        btn_mobile.setText(oldmobile);
        userSettingCB = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络", Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() == -103) {
                    Toast.makeText(aq.getContext(), msg_error,
                            Toast.LENGTH_LONG).show();
                } else {
                    if (status.getCode() != 200) {
                        Toast.makeText(aq.getContext(),
                                "网络异常:" + status.getCode(), Toast.LENGTH_LONG)
                                .show();
                    } else {

                        onSuccess(html);

                    }
                }
            }
        };
        uploadHeadimg = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(UserSettingActivity.this, "网络异常,请检查网络", Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_LONG).show();
                } else {
                    try {
                        if (html.getBoolean("isSuccess")) {
                            Toast.makeText(aq.getContext(), "上传成功",
                                    Toast.LENGTH_LONG).show();
                            btn_headimg.setImageBitmap(photo);
                        } else {
                            Toast.makeText(aq.getContext(),
                                    html.getString("errors"), Toast.LENGTH_LONG)
                                    .show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        };
        userSettingAction();
    }

    @Click
    void btn_headimg() {
        dialog = new ActionSheetDialog(this, new String[]{take_photo,
                from_photos}, null);
        dialog.titleTextColor(red).itemTextColor(blacktext).cornerRadius(0)
                .show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                switch (position) {
                    case 0:
                        Intent intentFromCapture = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        // 判断存储卡是否可以用，可用进行存储
                        intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                                .fromFile(new File(Environment
                                        .getExternalStorageDirectory(),
                                        IMAGE_FILE_NAME)));
                        startActivityForResult(intentFromCapture,
                                AVATAR_REQUEST_CODE);

                        break;
                    case 1:
                        Intent intentFromGallery = new Intent();
                        intentFromGallery.setType("image/*"); // 设置文件类型
                        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(intentFromGallery,
                                GALLERY_AVATAR_REQUEST_CODE);
                        break;
                }
                dialog.dismiss();
            }
        });
    }

    @OnActivityResult(REQUEST_CODE)
    void onResult(Intent data) {
        if (data != null) {
            boolean flag = data.getBooleanExtra("flag", false);
            if (flag) {
                userSettingAction();
            }

        }
    }

    @OnActivityResult(GALLERY_AVATAR_REQUEST_CODE)
    void onResultGallery(int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        if (data != null) {
            Intent intent = CommonUtils.startPhotoZoom(data.getData());
            startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
        }
    }

    @OnActivityResult(AVATAR_REQUEST_CODE)
    void onResultTakeAvatar(int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        File tempFile = new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME);
        Intent intent = CommonUtils.startPhotoZoom(Uri.fromFile(tempFile));
        startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
    }

    @OnActivityResult(PHOTO_PICKED_WITH_DATA)
    void onResultGetAvatar(int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        if (data != null) {
            setImageToView(data);
        }
    }

    private void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            photo = extras.getParcelable("data");
            String temp = "";
            try {
                temp = CommonUtils.encodeBase64File(CommonUtils
                        .saveBitmap(photo));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            uploadAction(temp);
        }
    }

    /**
     * send sms authcode request
     *
     * @throws UnsupportedEncodingException
     */
    private void userSettingAction() {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", oldmobile));
        CommonUtils.postRequest(get_user_setting_action, aq, userSettingCB,
                pairs);
    }

    /**
     * login request
     *
     * @throws UnsupportedEncodingException
     */
    private void uploadAction(String avatar) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", oldmobile));
        pairs.add(new BasicNameValuePair("avatar", avatar));
        // img
        CommonUtils.postRequest(upload_avatar_action, aq, uploadHeadimg, pairs);

    }

    // save the mobile temporarily ,if login successful ,save into the sp,for
    // keeping the login state

    void onSuccess(JSONObject obj) {
        String headimgUrl = getJsonString(obj, "iconPhotoUrl");
        if (!"".equals(headimgUrl)) {
            aq.id(btn_headimg).image(headimgUrl, true,
                    true, 200, 0, null, Constants.FADE_IN);

        }
        btn_name.setText(getJsonString(obj, "userName"));
        btn_mobile.setText(oldmobile);
    }

    @Click
    void btn_name() {
        ModifyNickNameActivity_.intent(this).extra("oldname", btn_name.getText().toString()).startForResult(REQUEST_CODE);
    }

    @Click
    void btn_mobile() {
        ModifyMobileActivity_.intent(this).startForResult(REQUEST_CODE);
    }

    @Click
    void btn_pwd() {
        ModifyPWDActivity_.intent(this).startForResult(REQUEST_CODE);
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        Intent intent = new Intent();
        intent.putExtra("flag", false);
        this.setResult(RESULT_OK, intent);
        this.finish();
    }

    @Click
    void btn_back() {
        onBackPressed();
    }

    @Click
    void exit_login() {
        dialog1();

    }

    private void dialog1() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("是否确认退出?"); //设置内容
        builder.setIcon(R.mipmap.ic_launcher);//设置图标，图片id即可
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                pref.clear();
                Intent intent = new Intent(UserSettingActivity.this, UserInfoActivity_.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
                dialog.dismiss(); //关闭dialog
//                Toast.makeText(UserSettingActivity.this, "确认" + which, Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
//                Toast.makeText(UserSettingActivity.this, "取消" + which, Toast.LENGTH_SHORT).show();
            }
        });

//        builder.setNeutralButton("忽略", new DialogInterface.OnClickListener() {//设置忽略按钮
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//                Toast.makeText(UserSettingActivity.this, "忽略" + which, Toast.LENGTH_SHORT).show();
//            }
//        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }
}
